package com.petiot.rabbitmq;

import java.io.IOException;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONException;
import org.json.JSONObject;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.petiot.ui.fragment.Home2Fra;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class PushService extends IntentService {

	
	public static final String TAG = "WavCamPushService";
	private ScheduledExecutorService executorService;
	private static final int ThreadPoolSize = 1;
	
	
	private static final int mNotificationId = 10;
	private SQLiteDatabase db;
	private PendingIntent pedingIntent;
	
	private static final int RequestCode = 20;
	MainActivity zzzz = new MainActivity();
	private String mCorrId;
	private String mDeviceUid;
	private String mSessionKey;
	private String mResponseQueue;
	private int mHeartBeatTimer = -1;
	private static final String EXCHANGE_NAME = "petiot.direct";
	
	String group_id = "A0000";
	String myclient_uid = "ZHUWEI_WAVIOT_VDEVICE_20151111_1";
	public WavIoTClient waviotClient = new WavIoTClient(group_id, myclient_uid);
	public Home2Fra canvas = new Home2Fra();

	public interface PushMsgCallback{
		
		public void callBack(String msg, String targetUid);
		public boolean doresLogin(Channel channel, String consumerTag, Envelope envelope, BasicProperties properties, JSONObject body);
		public void callBackUI(String string, String mDeviceUid);
	}
	
	
	private PushMsgCallback callBack = new PushMsgCallback()
	{

		@Override
		public void callBack(String msg, String targetUid) {
			// TODO Auto-generated method stub
			Log.d(TAG, "pushMsg:" + msg+"; uid:" + targetUid);
			//canvas.drawTable(msg);
			
			/**
			try {
				OrderedJSONObject one = new OrderedJSONObject(msg);
				
				org.apache.wink.json4j.JSONObject header = one.getJSONObject("header");
				String msgIdValue = header.getString("msgID");
				if(msgIdValue.equals("ipcamEvent"))
				{
					OrderedJSONObject body = (OrderedJSONObject) one.getJSONObject("body");
					String hashCode = JSONUtil.reqLoginHMACMD5_HashCode(Constants.HMAC_MD5_KEY, JSONUtil.getValueFromOrderedJson(body));
					hashCode = JSONUtil.dealStr(hashCode);
					if(!hashCode.equals(header.getString("hashcode")))
					{
						Log.e(TAG, "Invalid hash code ");
					}else
					{
						
						String eventAction = body.getString("eventAction");
						String eventType = body.getString("eventType");
						String targetUID = body.getString("targetUID");
						String eventTime = body.getString("eventTime");
						
						StringBuffer title = new StringBuffer();
						Formatter formatter = new Formatter(title, Locale.US);
						formatter.format("%s ipcamEvent ", targetUID);
						formatter.close();
						
						StringBuffer content = new StringBuffer();
						Formatter contentFormatter = new Formatter(content,Locale.US);
						contentFormatter.format(" %s  happend at  %s ", eventAction, eventTime);
						contentFormatter.close();
						
						saveEvent(eventAction,eventType,targetUid,eventTime);
						constructANotification(title.toString(), content.toString(),pedingIntent);
						
						
					}
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
			**/
		
			
			
		}

		@Override
		public boolean doresLogin(Channel channel, String consumerTag, Envelope envelope, BasicProperties properties,
				JSONObject body) {
			// TODO Auto-generated method stub
			String corrId = properties.getCorrelationId();
			if(!mCorrId.equals(corrId))
			{
				Log.e(TAG,  "curUid: " + mDeviceUid+",corr_id :"+mCorrId+" , is not matched " + corrId);
				return false;
			}
			

			try {
				if(body.getJSONObject("body").getString("retCode").equals("0000"))
				{
					JSONObject jsonBody = body.getJSONObject("body");
					mSessionKey = jsonBody.getString("sessionKey");
					
					mHeartBeatTimer =jsonBody.getInt("heartbeatPeriod");
					channel.queueBind(mResponseQueue, EXCHANGE_NAME, mSessionKey);
					Log.d(TAG, "mSessionKey mSessionKey, mSessionKey:" + mSessionKey);
					return true;
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			return false;
		}

		@Override
		public void callBackUI(String string, String mDeviceUid) {
			// TODO Auto-generated method stub
			//canvas.drawTable(string);
		}
		
	};
	/**
	private void constructANotification(String title, String content,PendingIntent pedingIntent)
	{
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
		mBuilder.setSmallIcon(R.drawable.app_icon);
		mBuilder.setContentTitle(title);
		mBuilder.setContentText(content);
		mBuilder.setContentIntent(pedingIntent);
		
		NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.notify(mNotificationId,mBuilder.getNotification());
	}
	**/
	
	
	
	public PushService() {
		super("PushService");
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// TODO Auto-generated method stub
		
		//PushMessageDbHelper dbHelper = new PushMessageDbHelper(this);
		//db = dbHelper.getWritableDatabase();
		Bundle bundle = intent.getExtras();
		String number = bundle.getString("number");
		String password = bundle.getString("pwd");
		
		
		if (waviotClient.initAmqpSessionSsl("121.199.26.216", 5671, "petiot", "petiot1886", "petiot.wavlink"))
		{
			Log.v(TAG, "创建connection成功了");
			waviotClient.addNewDevice("ZHUWEI_WAVIOT_VDEVICE_20151111_1", number, password, callBack);
			Log.v(TAG, "添加了一台设备");
			
			final Runnable command = new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					System.out.println("11111111111");
					List<WavIoTDevice> devices = waviotClient.getDevices();
					Log.e(TAG, "device = " + devices);
					for(WavIoTDevice one : devices)
					{
						System.out.println("2222222222");
						try {
							System.out.println("Channel = " + waviotClient.getChannel());
							one.doSession(waviotClient.getChannel(), waviotClient.getClientUid());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
				
			};
			executorService = Executors.newScheduledThreadPool(ThreadPoolSize);
			executorService.scheduleAtFixedRate(command, 0, 60, TimeUnit.SECONDS);
			Intent intentdd = new Intent();
			intentdd.setAction("login_succsess");
			sendBroadcast(intentdd);
		} else {
			Log.e(TAG, "AMQP Connection Failure.");
			Intent intentcc = new Intent();
			intentcc.setAction("login_failure");
			sendBroadcast(intentcc);
		}
		
		//Intent targetIntent = new Intent(getApplicationContext(),PushMessageDetailActivity.class);
		//pedingIntent = PendingIntent.getActivity(getApplicationContext(), RequestCode, targetIntent, 
				//Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
		
	}
	/**
	private void saveEvent(String eventAction,String eventType, String targetUid,String eventTime)
	{
		ContentValues value = new ContentValues();
		value.put(PushMessage.MessageEntry.COLUMN_NAME_EVENT_ACTION, eventAction);
		value.put(MessageEntry.COLUMN_NAME_EVENT_TYPE, eventType);
		value.put(MessageEntry.COLUMN_NAME_TARGET_UID, targetUid);
		value.put(MessageEntry.COLUMN_NAME_EVENT_TIME, eventTime);
		db.insert(MessageEntry.TABLE_NAME, MessageEntry.COLUMN_NAME_NULLABLE, value);
		
	}
	**/
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		Log.d(TAG, "pushService destroy");
		if(db != null)
		{
			db.close();
		}
	
//		try {
//			waviotClient.cancelConsumer();
//			waviotClient.quit();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

	
}
